<template>
  <div class='sub-category'>
    <div class="container">
      <!-- 面包屑导航 -->
      <SubBread></SubBread>
      <!-- 条件筛选区 -->
      <SubFilter @filter-change="filterChangeHandler"></SubFilter>
      <!-- 结果区域 -->
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sort-change="sortChangeHandler"></SubSort>
        <!-- 列表 -->
        <ul>
          <li v-for="good in goodsData" :key="good.id">
            <GoodsItem :good="good" />
          </li>
        </ul>
        <!-- 无限加载组件 -->
        <xtx-infinite-loading v-if="goodsData.length" @load="getData" :loading="loading" :finished="finished"
          finished-text="没有更多了" />
      </div>
    </div>
  </div>
</template>

<script setup>
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort'
import GoodsItem from './components/goods-item.vue'
import { ref, watch } from 'vue'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
const route = useRoute()
const loading = ref(false)
const finished = ref(false)
// 基本查询参数
let reqParams = {
  page: 1,
  pageSize: 20,
  categoryId: null
}
// 获取二级分类商品的数据的方法
// 商品数据
const goodsData = ref([])
const getGoods = async () => {
  // 获取当前页的数据
  const { result } = await findSubCategoryGoods(reqParams)
  if (result.items.length) {
    // 合并数据
    goodsData.value = [...goodsData.value, ...result.items]
    reqParams.page++
    // console.log(goodsData.value)
  } else {
    // 没有更多数据
    finished.value = true
  }
}
// 监听二级分类id的变化来获取数据
watch(() => route.params.id, newVal => {
  if (newVal && route.path === `/cate/sub/${route.params.id}`) {
    // 数据置空
    goodsData.value = []
    // 从第1页开始请求
    reqParams.page = 1
    // 重新获取分类id
    reqParams.categoryId = newVal
    finished.value = false
    loading.value = false
    getGoods()
  }
}, { immediate: true })
// 加载更多
function getData() {
  getGoods()
}

// 过滤条件发生改变时
function filterChangeHandler(filterParams) {
  // 和reqParams组合在一起形成新的搜索条件
  reqParams = { ...reqParams, ...filterParams }
  // 重新发起请求
  getGoods()
}
// 排序规则发生改变时
function sortChangeHandler(sortParams) {
  // 和reqParams组合在一起形成新的搜索条件
  reqParams = { ...reqParams, ...sortParams }
  // 重新发起请求
  getGoods()
}

</script>

<style lang="less" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;

  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;

    li {
      margin-right: 20px;
      margin-bottom: 20px;

      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>